package com.benworks.test.easymock.exchange;

import java.io.IOException;

/**
 * Currency 类设计的一些重点可能不容易一下子看出来。汇率是从这个类之外 传递进来的，并不是在类内部构造的。因此，很有必要为汇率创建
 * mock，这样在运行测试时就不需要与真正的汇率服务器通信。这还使客户机应用程序能够使用不同的汇率数据源。
 * 
 * @author http://www.ibm.com/developerworks/cn/java/j-easymock.html
 *
 */
public class Currency {
	private String units;
	private long amount;
	private int cents;

	public Currency(double amount, String code) {
		this.units = code;
		setAmount(amount);
	}

	private void setAmount(double amount) {
		this.amount = new Double(amount).longValue();
		this.cents = (int) ((amount * 100.0) % 100);
	}

	public Currency toEuros(ExchangeRate converter) {
		if ("EUR".equals(units))
			return this;
		else {
			double input = amount + cents / 100.0;
			double rate;
			try {
				rate = converter.getRate(units, "EUR");
				double output = input * rate;
				return new Currency(output, "EUR");
			} catch (IOException ex) {
				return null;
			}
		}
	}

	public boolean equals(Object o) {
		if (o instanceof Currency) {
			Currency other = (Currency) o;
			return this.units.equals(other.units) && this.amount == other.amount && this.cents == other.cents;
		}
		return false;
	}

	public String toString() {
		return amount + "." + Math.abs(cents) + " " + units;
	}
}
